const fs = require('fs')
const exec = require('child_process').exec
const path = require('path')

function runShell(shell) {
  return new Promise((resolve, reject) => {
    exec(shell, (error, stdout, stderr) => {
      if (error) {
        reject(error)
        return
      }
      resolve({
        error,
        stdout,
        stderr
      })
    })
  })
}

/**
 * 重置端口
 * @param {*} rport
 * @param {*} callback
 */
function resetPort(rport, callback) {
  const filePath = './dist/index.html'
  const myHtml = fs.readFileSync(filePath, 'utf-8')
  const index = myHtml.indexOf('window.ExmdViewPort')
  const str = myHtml.substring(index, myHtml.length - 1)
  const str2 = str.substring(0, str.indexOf('</script>'))
  const port = str2.trim().split('=')[1]
  const result = myHtml.replace(port, ' ' + rport)
  fs.writeFile(filePath, result, function (error) {
    if (error) {
      console.log('写入失败')
    } else {
      callback()
    }
  })
}

module.exports = {
  resetPort,
  runShell
}
